package com.common.autocode.mysql;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.common.autocode.xml.XmlUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class CommonParser {
	private static final Log log = LogFactory.getLog(CommonParser.class);
	private static Configuration cfg = new Configuration();
	private static Template template = null;
	private static final String baseTemplatePath = "../template";
	
	static {
		cfg.setClassForTemplateLoading(CommonParser.class, baseTemplatePath);
	}

	private static void create(String templateName, String fileDirPath,
			String targetFile,Object data) throws Exception {
		System.out.println(fileDirPath);
		File file = new File(fileDirPath + targetFile);
		if (!(file.exists())) {
			new File(file.getParent()).mkdirs();
		} else {
			log.info("替换文件:" + file.getAbsolutePath());
		}
		
		template = cfg.getTemplate(templateName);
		FileOutputStream fos = new FileOutputStream(file);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				fos, "UTF-8"));
        template.process(data, writer);
         
        writer.flush();
		writer.close();
		fos.close();
		log.info("生成文件：" + file.getAbsolutePath());
	}
	
	public static Map writeEntity(String packageName,String className,Object data,Object childClassNames){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        root.put("attrs", data);
        root.put("childClassNames", childClassNames);
        try {
			create("EntityTemplate.ftl", "src/"+packageName.replaceAll("\\.", "/")+"/vo/", className+".java",root);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
        return root;
	}
	
	public static void writeMapper(String packageName,String className,String tableName,List<ColumnData> data,Map childInfos,Map tableInfo){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        root.put("tableName", tableName);
        root.put("attrs", data);
        root.put("childInfos", childInfos);
        root.put("tableInfos", tableInfo);
        try {
			create("MapperTemplate_mysql.ftl", "src/"+packageName.replaceAll("\\.", "/")+"/dao/", className+"Mapper.xml",root);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void writeDao(String packageName,String className){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        try {
			create("DaoTemplate.ftl", "src/"+packageName.replaceAll("\\.", "/")+"/dao/", className+"Dao.java",root);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void writeService(String packageName,String className){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        try {
			create("ServiceTemplate.ftl", "src/"+packageName.replaceAll("\\.", "/")+"/service/", className+"Service.java",root);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void writeController(String packageName,String className,List<ColumnData> data){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        root.put("attrs", data);
        try {
			create("ControllerTemplate.ftl", "src/"+packageName.replaceAll("\\.", "/")+"/controller/", className+"Controller.java",root);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void writeJSP(String packageName,String className,List<ColumnData> data){
		Map<String,Object> root = new HashMap<String, Object>();
        root.put("packageName", packageName);
        root.put("className", className);
        root.put("attrs", data);
        try {
			create("jsp/ListJSPTemplate.ftl", "WebContent/WEB-INF/pages/"+packageName.replaceAll("\\.", "/")+"/", className+"_list.jsp",root);
			create("jsp/ViewJSPTemplate.ftl", "WebContent/WEB-INF/pages/"+packageName.replaceAll("\\.", "/")+"/", className+"_view.jsp",root);
			create("jsp/EditJSPTemplate.ftl", "WebContent/WEB-INF/pages/"+packageName.replaceAll("\\.", "/")+"/", className+"_edit.jsp",root);
        } catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void columnToClass(String uri,String username,String pwd,String table,String packageName){
		DbMetaData d = new DbMetaData();
		d.setDbInfo(uri,username,pwd);
		List list;
		try {
			String schema = uri.substring(uri.lastIndexOf("/")+1, (uri.indexOf("?")==-1?uri.length():uri.indexOf("?")));
			list = d.getMysqlTablePdmCloumns(schema,table);
			//查询子表
			List<ChildColumnData> childTables = d.getChildTablePdmCloumns(schema,table);
			List childClassNames = new ArrayList();
			Map childInfos = new HashMap();
			Map tableInfo = new HashMap();
			if(!childTables.isEmpty()){
				for(ChildColumnData childTable : childTables){
					List childList = d.getMysqlTablePdmCloumns(schema,childTable.getTableName());
					System.out.println("childList: "+childList);
					String temp = childTable.getTableName().replace("px_", "");
					String className = temp.substring(0, 1).toUpperCase()+temp.substring(1, temp.length());
					className = className.replace("_", "");
					writeEntity(packageName, className,childList,null);
					childClassNames.add(className);
					//Mapper文件子表信息
					
					tableInfo.put(className, childList);
					childInfos.put(className,childTable);
				}
			}
			
			String temp = table.replace("px_", "");
			String className = temp.substring(0, 1).toUpperCase()+temp.substring(1, temp.length());
			className = className.replace("_", "");
			
			writeEntity(packageName, className,list,childClassNames);
		
			writeMapper(packageName,className,table,list,childInfos,tableInfo);
			
			writeDao(packageName,className);
			
			writeService(packageName,className);
		
			writeController(packageName,className,list);
			
			writeJSP(packageName,className,list);
			
			XmlUtils.modifySpringBeanXml(packageName);
			XmlUtils.writerTilesXml(packageName, className);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/*public static String getProjectPath() {
		String path = System.getProperty("user.dir").replace("\\", "/") + "/";
		return path;
	}*/
}
